package dyy.zc.computergradeexam.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import dyy.zc.computergradeexam.R;
import dyy.zc.computergradeexam.base.BaseActivity;
import dyy.zc.computergradeexam.bean.ChooseInfo;
import dyy.zc.computergradeexam.bean.TianKong;
import dyy.zc.computergradeexam.bean.WrongQuestion;
import dyy.zc.computergradeexam.utils.BmobUtils;
import dyy.zc.computergradeexam.utils.ToastUtils;
import dyy.zc.computergradeexam.views.CollectViewPager;
import dyy.zc.computergradeexam.views.EmptyView;
import dyy.zc.computergradeexam.views.MyAlertDialog;

public class TianKongActivity extends BaseActivity implements View.OnClickListener {
    private TextView title,right;
    private TextView tvQuestion;
    private TextView tvAnswerArea;
    private TextView tvShowAnswer;
    private LinearLayout llAnswerArea;
    private ImageView collect;
    private boolean collectState = false;
    public WrongQuestion wrongQuestion;
    private boolean checkWrong;
    private EmptyView emptyView;
    private List<String> wrongIdS = new ArrayList<>();
    private boolean isHas = false;
    private List<TianKong> list = new ArrayList<>();
    private List<TianKong> collectList = new ArrayList<>();
    private TianKong tianKong;
    private BmobUtils bmobUtils;
    private int count = 0;
    private ScrollView scrollView;
    private EditText myanswer;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    if (checkWrong){//展示错题
                        if (wrongQuestion == null||wrongQuestion.getId().size()==0){
                            emptyView.setNotify("暂无收藏");
                        }else {
                            wrongIdS.clear();
                            wrongIdS.addAll(wrongQuestion.getId());
                            for (TianKong tianKong:list){
                                for (String id:wrongIdS){
                                    if (tianKong.getObjectId().equals(id)){
                                        collectList.add(tianKong);
                                    }
                                }
                            }
                            scrollView.setVisibility(View.VISIBLE);
                            setQuestion();
                        }
                    }else {
                        if (wrongQuestion == null){
                            isHas = false;
                            wrongQuestion = new WrongQuestion();
                            wrongQuestion.setType("2");
                            wrongQuestion.setAccount(loginuser.getAccount());
                            wrongQuestion.setId(wrongIdS);
                        }else {
                            wrongIdS.clear();
                            wrongIdS.addAll(wrongQuestion.getId());
                            isHas = true;
                        }
                        scrollView.setVisibility(View.VISIBLE);
                        setQuestion();
                    }
                    dialog.dismiss();
                    break;
                case 4://保存错题
                    dialog.dismiss();
                    finish();
                    break;
            }
        }
    };

    private void setQuestion() {
        myanswer.setText("");
        if (checkWrong){
            tianKong = collectList.get(count);
            collect.setImageResource(R.mipmap.quanxing);
        }else {
            tianKong = list.get(count);
            if (wrongIdS.contains(tianKong.getObjectId())){
                collectState = true;
                collect.setImageResource(R.mipmap.quanxing);
            }else {
                collectState = false;
                collect.setImageResource(R.mipmap.banxing);
            }
        }
        tvQuestion.setText((count+1)+"、"+tianKong.getQuestion());
        tvAnswerArea.setText(tianKong.getAnswer());
    }

    @Override
    protected void findViewByIDS() {
        emptyView = new EmptyView(this);
        title = (TextView) findViewById(R.id.top_tv_title);
        right = (TextView) findViewById(R.id.top_tv_right);
        tvQuestion = (TextView) findViewById(R.id.tv_question);
        tvAnswerArea = (TextView) findViewById(R.id.tv_Answer);
        tvShowAnswer = (TextView) findViewById(R.id.tv_ShowAnswer);
        llAnswerArea = (LinearLayout) findViewById(R.id.ll_AnswerArea);
        scrollView = findViewsById(R.id.scrollView);
        collect = findViewsById(R.id.collect);
        myanswer = findViewsById(R.id.myanswer);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tian_kong);
        initData();
        bind();
    }

    private void bind() {
        findViewsById(R.id.top_rl_right).setOnClickListener(this);
        if (checkWrong){

        }else {
            tvShowAnswer.setOnClickListener(this);
            collect.setOnClickListener(this);
        }
    }


    private void initData() {
        scrollView.setVisibility(View.GONE);
        right.setText("下一题");
        right.setVisibility(View.VISIBLE);
        bmobUtils = new BmobUtils(this);
        dialog = ProgressDialog.show(this,null,"正在加载题目......");
        bmobUtils.getTianKongInfo(loginuser.getAccount(),"2",list,1,handler);
        Intent intent = getIntent();
        if (intent.getIntExtra("type",0)==1){//展示收藏题
            checkWrong = true;
            title.setText("我的收藏");
            llAnswerArea.setVisibility(View.VISIBLE);
        }else {
            checkWrong = false;
            title.setText("查看题目");
        }

        //读取raw资源文件获得一个InputStream用来读取文件用的
        //这个只要获取一次
//        InputStream inputStream = getResources().openRawResource(R.raw.tiankong);
//        getString(inputStream);
        //bmobUtils.saveChooseInfo(list,1,handler);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_ShowAnswer:
                llAnswerArea.setVisibility(View.VISIBLE);
                break;
            case R.id.top_rl_right:
                count++;
                if (!checkWrong){
                    llAnswerArea.setVisibility(View.GONE);
                    if (list.size() > count){
                        setQuestion();
                    }else {
                        ToastUtils.shortToast(TianKongActivity.this,"没有下一题啦~~~");
                    }
                }else {
                    if (collectList.size() > count){
                        setQuestion();
                    }else {
                        ToastUtils.shortToast(TianKongActivity.this,"没有下一题啦~~~");
                    }
                }

                break;
            case R.id.collect:
                String id = list.get(count).getObjectId();
                if (collectState){
                    collectState = false;
                    wrongIdS.remove(id);
                    collect.setImageResource(R.mipmap.banxing);
                }else {
                    collectState = true;
                    collect.setImageResource(R.mipmap.quanxing);
                    wrongIdS.add(id);
                }
                break;
        }
    }

    // 捕获返回键的方法1
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        && event.getRepeatCount() == 0
        if (checkWrong) {//去掉返回的弹窗
            finish();
        } else {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                // 按下BACK，同时没有重复
                back();
            }
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void backClick(View view) {
        if (checkWrong){
           finish();
        }else {
            back();
        }

    }

    public void back(){
        if (count >= list.size()){
            saveWrong();
        }else {
            MyAlertDialog logDialog = new MyAlertDialog(this);
            logDialog.builder()
                    .setTitle("退出提示")
                    .setMsg("题目还没有做完呢")
                    .setNegativeButton("火大不做了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            saveWrong();
                        }
                    })
                    .setPositiveButton("开个玩笑", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    })
                    .show();
        }
    }

    /**
     * 保存错题
     */
    public void saveWrong(){
        dialog = ProgressDialog.show(this,null,"正在保存收藏");
        wrongQuestion.setId(wrongIdS);
        if (isHas){
            bmobUtils.updateWrongQuestion(wrongQuestion,4,handler);
        }else {
            bmobUtils.saveWrongQuestion(wrongQuestion,4,handler);
        }
    }

//    public void getString(InputStream inputStream) {
//        //将InputStream转换成inputStreamReader并设置读取的编码格式utf-8
//        InputStreamReader inputStreamReader = null;
//        try {
//            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
//        } catch (UnsupportedEncodingException e1) {
//            e1.printStackTrace();
//        }
//        //再将InputStreamReader封装成BufferedReader
//        BufferedReader reader = new BufferedReader(inputStreamReader);
//        //申明字符串，用来保存读取的数据
//        StringBuffer sb = new StringBuffer("");
//        //这个是申明读取的行数，一般都是循环读取的，你把删掉了。。。。。
//        //当后面没有数据之后，line会返回null，根据这个判断是不是读取到文本末尾了
//        String line;
//        String first = "*";
//        String QUES= "@";
//        boolean over = false;
//        tianKong = new TianKong();
//        sb.setLength(0);
//        int count = 0;
//        try {
//
//            //一般是这样的，读一行就添加一行到字符串末尾
//            while ((line = reader.readLine()) != null) {
//                if (line.equals(first)){
//                    if (over){
//                        list.add(tianKong);
////                        Log.e("Question",tianKong.getQuestion());
//                        over = false;
//
//                    }
////                    Log.e("line",line);
//                    tianKong = new TianKong();
//                    sb.setLength(0);
//                }else if(line.equals(QUES)){
//                    tianKong.setQuestion(String.valueOf(sb));
//                    sb.setLength(0);
//                    count = 1;
//                }else {
//                    switch (count){
//                        case 0:
//                            sb.append(line);
//                            break;
//                        case 1:
//                            tianKong.setAnswer(line);
//                            sb.setLength(0);
//                            count = 0;
//                            over = true;
//                            break;
//
//                    }
//                }
////                switch (line){
////                    case "quse":
////                        Log.e("line",line);
////                        if (over){
////                            chooseInfoList.add(chooseInfo);
////                            Log.e("Question",chooseInfo.getQuestion());
////                            over = false;
////                        }
////                        Log.e("line",line);
////                        chooseInfo = new ChooseInfo();
////                        sb.setLength(0);
////                        break;
////                    case "@":
////                        chooseInfo.setQuestion(String.valueOf(sb));
////                        sb.setLength(0);
////                        count = 1;
////                        break;
////                    default:
////
////                        break;
////                }
//
//            }
//
//            //这个是读取一行的
////            line = reader.readLine();
////            //将读取的一行加入字符串末尾
////            sb.append(line);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }


}
